<?php
require_once(_PS_MODULE_DIR_.'prestatheme/models/Project.php');
require_once(_PS_MODULE_DIR_.'prestatheme/models/PrestathemeCms.php');
require_once(_PS_MODULE_DIR_.'prestatheme/API/models/PrestathemeEditor.php');
class PrestathemeMyprojectsModuleFrontController extends ModuleFrontController
{
	public $auth = true;
	public $ssl  = true;
	public $display_column_right = false;

	/**
	 * @see FrontController::initContent()
	 */
	public function initContent()
	{
		parent::initContent();
        
        $this->context->controller->addCSS($this->module->getPathUri() .'/views/css/style.css');
		$this->context->smarty->assign(array(
			'myProjects' => array(),
			'this_path' => $this->module->getPathUri(),
			'this_path_ssl' => Tools::getShopDomainSsl(true, true).__PS_BASE_URI__.'modules/'.$this->module->name.'/'
		));
        
        //if editing a project
        if ($_SERVER['REQUEST_METHOD'] == 'POST') 
        {
            if ($project = Tools::getValue('project', false)) 
            {
                try
                {
                    $projectObj = (!empty($project['id_project'])) ? new Project((int)$project['id_project']) : new Project();
                    $projectObj->id_owner    = $this->context->customer->id;
                    $projectObj->active      = true;
                    $projectObj->description = $project['description'];
                    $projectObj->id_cms      = (int)$project['id_cms'];
                    $projectObj->is_public   = isset($project['is_public']) ? true : false;
                    $projectObj->name        = $project['name'];
                    
					if (empty($projectObj->name))
					{
						$this->errors[] = Tools::displayError('Project name is required');
						throw new Exception('Invalid project name');
					}
					elseif (!Validate::isTplName($projectObj->name))
					{
						$this->errors[] = Tools::displayError('Invalid project name');
						$this->errors[] = sprintf(Tools::displayError('%s is not a valid theme name. Alpanumeric chacarters and "-", "_" are those which are allow.'), '<b>'. $projectObj->name .'</b>');
						throw new Exception('Invalid project name');
					}
                    elseif ($projectObj->save(true))
                    {
                        if (Tools::isSubmit('createAndRunEditor'))
                            $this->runEditor($projectObj->id);
                        else
                            Tools::redirect($this->context->link->getModuleLink('prestatheme', 'myprojects', array('status' => 'success'), true));
                    }
                    else
                    {
                        Tools::redirect($this->context->link->getModuleLink('prestatheme', 'myprojects', array('status' => 'failed'), true));
                    }
                }
                catch (Exception $ex)
                {
					$this->errors[] = Tools::displayError('An error occurs while editing the project.');
					$this->context->smarty->assign('project', $projectObj);
					$this->context->smarty->assign('id_shop', Context::getContext()->shop->id);
					$this->context->smarty->assign('title', NULL);
					$this->context->smarty->assign('cmsList', PrestathemeCms::findAll());
					$this->setTemplate('edit-project.tpl');
                }
            }
        }
        
        //if requesting to view or edit a project
        elseif ((Tools::isSubmit('view') AND Tools::isSubmit('id_project')) OR Tools::isSubmit('edit'))
        {
            if (Tools::isSubmit('id_project'))
            {
                $projectObj = new Project((int)Tools::getValue('id_project'));
                $projectObj->product = new Product($projectObj->id_product, true, Context::getContext()->language->id);
                if (!$projectObj->product->id)
                {
                    $projectObj->product = NULL;
                }
                $title = $projectObj->name;
            }
            else
            {
                $projectObj = new Project();
                $title = NULL;
            }
            $this->context->smarty->assign('project', $projectObj);
            $this->context->smarty->assign('id_shop', Context::getContext()->shop->id);
            $this->context->smarty->assign('title', $title);
            $this->context->smarty->assign('cmsList', PrestathemeCms::findAll());
            
            if (Tools::isSubmit('edit'))
                $this->setTemplate('edit-project.tpl');
            else
                $this->setTemplate('view-project.tpl');
        }
        
        //run the theme editor
        elseif (Tools::isSubmit('run-editor') AND Tools::isSubmit('id_project'))
        {
            $projectObj = new Project((int)Tools::getValue('id_project'));
            $this->runEditor($projectObj->id);
        }
        
        //Generate the package wth the product associated
        elseif (Tools::isSubmit('make-package') AND Tools::isSubmit('id_project'))
        {
            require_once(_PS_MODULE_DIR_.'prestatheme/API/models/zip/Zip.php');
            $projectObj = new Project((int)Tools::getValue('id_project'));
            $prestaCMSObj = new PrestathemeCms($projectObj->id_cms);
            
            // 1- From data in database, we make the new css
            $styles = $projectObj->generateCSS();
            $styles = $projectObj->concatToGridPrestashopFile($prestaCMSObj->path.'/css/grid_prestashop.css', $styles);
            
            // 2- We make the zip file archiving the new theme
            $filesToAdd    = array('themes/'.$projectObj->name .'/css/grid_prestashop.css' => $styles);
            $filesToRemove = array($prestaCMSObj->path.'/css/grid_prestashop.css');
            $zipFileHandle = $projectObj->makePackage($prestaCMSObj->path, $filesToAdd, $filesToRemove);
            
            // 3- From the generated archive, we create the associated product
            $projectObj->makeProduct($zipFileHandle);
			$projectObj->product = new Product($projectObj->id_product, true, Context::getContext()->language->id);
			
			// 4-0 Redirect on the product page
            if (Tools::isSubmit('return') AND Tools::getValue('return') == 'product')
			{
				Tools::redirect($this->context->link->getProductLink($projectObj->product->id, $projectObj->product->link_rewrite, $projectObj->product->category, null, null, $this->context->shop->id));
			}
			
            // 4-1 display view
			else
			{
				if (!$projectObj->product->id)
				{
					$projectObj->product = NULL;
				}
				$this->context->smarty->assign('project', $projectObj);
				$this->context->smarty->assign('id_shop', Context::getContext()->shop->id);
				$this->context->smarty->assign('title', $projectObj->name);
				$this->context->smarty->assign('cmsList', PrestathemeCms::findAll());
				$this->setTemplate('view-project.tpl');
			}
        }
        
        //By default, display the list of projects
        else
        {
            $projects = Project::findByIdOwner($this->context->customer->id);
            $this->context->smarty->assign('projects', $projects);
            $this->setTemplate('my-projects.tpl');
        }
	}
    
    public function runEditor ($id_project)
    {
        $token  = md5('ZNSDie324dziffe_'. $this->context->customer->id .'_'. $id_project);
        $editor = new PrestathemeEditor((int)$id_project, $this->context->customer->id, $token, Language::getIsoById($this->context->language->id));
        
        Session::getInstance()->return_link = $this->context->link->getModuleLink('prestatheme', 'myprojects', array('make-package'=>'1', 'id_project'=>$id_project, 'return' => 'product'), true);
        Session::getInstance()->back_link = $this->context->link->getModuleLink('prestatheme', 'myprojects', array('view'=>'1', 'id_project'=>$id_project, 'return' => 'product'), true);
        
		$url = __PS_BASE_URI__ .'modules/prestatheme/API';
        header('Location: '. $url);
    }
}
